package com.morn.weibo.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.Log;

public class BitmapUtils {

	public static final int IMAGE_MAX_WIDTH = 596;
	public static final int IMAGE_MAX_HEIGHT = 1192;

	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
		if (bitmap != null) {
			Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
					bitmap.getHeight(), Config.ARGB_8888);
			Canvas canvas = new Canvas(output);

			final int color = 0xff424242;
			final Paint paint = new Paint();
			final Rect rect = new Rect(0, 0, bitmap.getWidth(),
					bitmap.getHeight());
			final RectF rectF = new RectF(rect);
			final float roundPx = 10;

			paint.setAntiAlias(true);
			canvas.drawARGB(0, 0, 0, 0);
			paint.setColor(color);
			canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

			paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
			canvas.drawBitmap(bitmap, rect, rect, paint);
			return output;
		} else
			return null;
	}

	public static Bitmap compressBitmap(File file, int MAX_WIDTH, int MAX_HEIGHT) {
		String filepath = file.getAbsolutePath();
		int scale = 1;
		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filepath, o);
		if (o.outWidth > MAX_WIDTH || o.outHeight > MAX_HEIGHT) {
			scale = (int) Math.pow(
					2.0,
					(int) Math.round(Math.log(MAX_WIDTH
							/ (double) Math.max(o.outHeight, o.outWidth))
							/ Math.log(0.5)));

		}
		o.inJustDecodeBounds = false;
		o.inSampleSize = scale;
		Bitmap bitmap = BitmapFactory.decodeFile(filepath, o);
		return bitmap;
	}

	public static File disposeImage(File file, Context context) {
		Bitmap bitmap = compressBitmap(file, IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT);
		File newFile = new File(context.getCacheDir(), "temp.jpg");
		if (newFile.exists()) {
			newFile.delete();
		}
		OutputStream out = null;
		try {
			out = new FileOutputStream(newFile);
			bitmap.compress(CompressFormat.JPEG, 100, out);
			Log.i("fanfou", "fileSize=" + newFile.length());
			return newFile;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
